<!--
 * @Date: 2025-10-15 23:03:35
 * @LastEditors: 贾二小 erxiao.jia@outlook.com
 * @LastEditTime: 2025-11-19 17:16:08
 * @FilePath: /admin-vue/src/views/admin/system/user/modules/user-role-operate-modal.vue
-->
<script setup lang="ts">
import { ref, watch } from 'vue'

const { userRoles, syncUserRoles } = useUser()
const { roles } = useRole()
const { loading: loading, startLoading, endLoading } = useLoading(false)

defineOptions({ name: 'UserRoleOperateModal' })

interface Props {
  /** 弹窗可见性 */
  visible: boolean
  /** 角色ID */
  id: number
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
}

const emit = defineEmits<Emits>()
const props = withDefaults(defineProps<Props>(), {})

const value = ref<number[]>([])

watch(
  () => props.visible,
  async (newValue) => {
    if (newValue) {
      value.value = await userRoles(props.id)
    }
  },
)

const handleModalConfirm = async () => {
  startLoading()
  try {
    const { success } = await syncUserRoles(props.id, value.value)
    handleModalClose(false)
  } finally {
    endLoading()
  }
}

const handleModalClose = (visible: boolean) => {
  emit('update:visible', visible)
}

//加载所有权限列表
const options = await roles()
</script>

<template>
  <ad-modal
    :visible="visible"
    :title="$t('modal.role')"
    :loading="loading"
    @update:visible="handleModalClose"
    @confirm="handleModalConfirm"
    class="max-w-md"
  >
    <n-transfer v-model:value="value" virtual-scroll :options="options" source-filterable />
  </ad-modal>
</template>

<style lang="scss" scoped></style>
